package com.liyu.config;

import com.rabbitmq.client.BuiltinExchangeType;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author 李誉
 * @date 2022-07-06 22:06
 * @description 死信队列
 */
@Component
public class DlxComment {


    public static final String DLX_EXCHANGE = "dlx.exchange.hello";

    public static final String DLX_QUEUE = "dlx.queue.hello";

    public static final String DLX_RK = "dlx.rk.hello";

    public static final String NORMAL_EXCHANGE = "normal.exchange.hello";

    public static final String NORMAL_QUEUE = "normal.queue.hello";

    public static final String NORMAL_RK = "normal.rk.hello";

    public static final String NORMAL_MAXLENGTH_QUEUE = "normal.queue.maxlength";

    public static final String NORMAL_MAXLENGTH_RK = "normal.rk.maxlength";

    /**
     * 普通交换机
     */
    @Bean("normalExchange")
    public Exchange normalExchange() {
        return new ExchangeBuilder(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT.getType()).build();
    }

    /**
     * 普通队列
     */
    @Bean("normalQueue")
    public Queue normalQueue() {
        // 注意：绑定死信队列和死信交换机
        return QueueBuilder.durable(NORMAL_QUEUE).deadLetterExchange(DLX_EXCHANGE).deadLetterRoutingKey(DLX_RK).build();
    }

    /**
     * 绑定普通队列到普通交换机
     */
    @Bean("normalBinding")
    public Binding normalBinding(Exchange normalExchange, Queue normalQueue) {
        return BindingBuilder.bind(normalQueue).to(normalExchange).with(NORMAL_RK).noargs();
    }

    /**
     * 普通队列（最大队列长度）
     */
    @Bean("normalMaxLengthQueue")
    public Queue normalMaxLengthQueue() {
        // 注意：绑定死信队列和死信交换机，并设置最大队列长度
        return QueueBuilder.durable(NORMAL_MAXLENGTH_QUEUE).deadLetterExchange(DLX_EXCHANGE).deadLetterRoutingKey(DLX_RK).maxLength(5).build();
    }

    /**
     * 绑定普通队列（最大队列长度）到普通交换机
     * @param normalExchange
     * @param normalMaxLengthQueue
     * @return
     */
    @Bean("normalMaxLengthBinding")
    public Binding normalMaxLengthBinding(Exchange normalExchange, Queue normalMaxLengthQueue) {
        return BindingBuilder.bind(normalMaxLengthQueue).to(normalExchange).with(NORMAL_MAXLENGTH_RK).noargs();
    }

    /**
     * 死信交换机
     */
    @Bean("dlxExchange")
    public Exchange dlxExchange(){
        return new ExchangeBuilder(DLX_EXCHANGE, BuiltinExchangeType.DIRECT.getType()).build();
    }

    /**
     * 死信队列
     */
    @Bean("dlxQueue")
    public Queue dlxQueue() {
        return QueueBuilder.durable(DLX_QUEUE).build();
    }

    /**
     * 绑定死信队列到死信交换机
     */
    @Bean("dlxBinding")
    public Binding dlxBinding(Exchange dlxExchange, Queue dlxQueue) {
        return BindingBuilder.bind(dlxQueue).to(dlxExchange).with(DLX_RK).noargs();
    }

}
